/*
 * Copyright (c) 2017. 杭州端点网络科技有限公司.  All rights reserved.
 */

package com.jiantong.web.core.cloud;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.google.common.collect.Sets;
import com.jiantong.web.core.cloud.service.FileServer;
import com.jiantong.web.core.cloud.service.impl.AliyunFileServer;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Set;
import java.util.UUID;

/**
 * aliyun oss 测试例子.
 *
 * API 调用过程按需求设置自己的 com.jiantong.web.core.cloud.OSSExample#ALLOW_EXT
 *
 * @author : panxin
 */
public class OSSExample {

    private static String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
    private static String accessKeyId = "UU60NderpiWvL8pO";
    private static String accessKeySecret = "XnEReA2mIHlDQEeQjAshEtODhvV78c";
    private static String bucketName = "dongjiantong";
    private static String uploadFile = "/your/path/file";
    private static String imageBaseUrl = "http://dongjiantong.oss-cn-hangzhou.aliyuncs.com";

    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormat.forPattern("yyyy/MM/dd");

    private static final Set<String> ALLOW_EXT = Sets.newHashSet(
            ".avi", ".3gp", ".mp4", // 视频格式
            "jpg", ".png", ".gif" // 图片格式
    );

    /**
     * main test
     *
     * @param args args
     * @throws Exception e
     */
    public static void main(String[] args) throws Exception {
        // 文件服务
        FileServer fileServer = new AliyunFileServer(endpoint, accessKeyId, accessKeySecret, bucketName);

        // 文件流
        File file = new File(uploadFile);
        InputStream inputStream = new FileInputStream(file);

        // 根据文件扩展名生成文件保存路径
        String ext = ".3gp";
        checkExt(ext);
        String path = generateSavePath(ext);

        // 上传文件, 返回文件相对路径
        path = fileServer.write(path, inputStream);

        // 文件路径(即文件下载地址, 图片地址)
        System.out.println("upload result path = " + imageBaseUrl + "/" + path);
    }

    /**
     * 检查文件格式
     *
     * @param ext 后缀名
     */
    private static void checkExt(String ext) {
        if (!ALLOW_EXT.contains(ext)) {
            throw new RuntimeException("file.ext.is.not.allowed");
        }
    }

    /**
     * 生成保存的文件路径
     *
     * @param ext 扩展名
     * @return 文件路径
     */
    private static String generateSavePath(String ext) {
        return DateTime.now().toString(DATE_FORMATTER) + "/" + UUID.randomUUID().toString() + "." + ext;
    }

    /**
     * 测试上传
     *
     * @throws Exception e
     */
    public static void testUpload() throws Exception {
        // 创建OSSClient实例
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

        // 读取上传
        String key = "<your-key>";
        File file = new File(uploadFile);
        InputStream inputStream = new FileInputStream(file);
        PutObjectResult putObject = ossClient.putObject(bucketName, key, inputStream);

        System.out.println(putObject);

        // 关闭client
        ossClient.shutdown();
    }

    /**
     * 测试下载
     *
     * @throws IOException e
     */
    public static void testDownload() throws IOException{
        // 创建OSSClient实例
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

        // 下载object到文件
        String key = "<your-key>";
        ossClient.getObject(new GetObjectRequest(bucketName, key), new File("</your/target/file/path>"));

        // 关闭client
        ossClient.shutdown();
    }

}
